define(function(require){
    $(function(){
    	/*---------- 流量资源——管理员 ----------*/
    	var position_id = semi.utils.getUrlParam('position_id');

        /* 表格 */
    	var bodyTemplate = ['<tr traffic_id="{traffic_id}" istate="">',
	    	                    '<td class="txtc"><a href="/trp/resource/main/?traffic={traffic_id}" title="{position_name}">{position_name}</a></td>',
	    	                    '<td class="txtc position_attrs">{position_attrs}</td>',
	    	                    '<td class="txtc position_size">{width}</td>',
	    	                    '<td class="txtc position_size">{height}</td>',
	    	                    '<td class="txtc">{max}</td>',
	    	                    '<td class="txtc media_name">{media_name}</td>',
	    	                    '<td class="txtc media_name">{media_attrs}</td>',
	    	                    '<td class="txtc circle" start="{start}" end="{end}">{start} 至 {end}</td>',
	    	                    '<td class="txtc bid_type">{bid_type}</td>',
	    	                    '<td class="txtc bid_price">{bid_price}</td>',
	    	                    '<td class="txtc pv">{pv}</td>',
	    	                    '<td class="txtc click">{click}</td>',
	    	                    '<td class="txtc shared">{shared}</td>',
	    	                    '<td class="txtc floor">{floor}</td>',
	    	                    '<td class="txtc floor" active="{active}"><div class="btn-group btn-group-sm"><button type="button" class="btn btn-success traffic-open">开</button><button type="button" class="btn btn-default traffic-close">关</button></div></td>',
		                     	'<td class="txtc">',
		                     		/*'<a class="ibtn showdetail" href="javascript:;" title="查看"><span class="glyphicon glyphicon-eye-open"></span></a>',*/
		                     		'<a class="ibtn showchart" href="javascript:;" title="查看报表"><span class="glyphicon glyphicon-list-alt"></span></a>',
		                     		'<a class="ibtn editbtn" href="javascript:;" title="修改"><span class="glyphicon glyphicon-pencil"></span></a>',
		                     		'<a class="ibtn delbtn" can_deleted="{can_deleted}" href="javascript:;" title="删除"><span class="glyphicon glyphicon-remove"></span></a>',
		                     		'<a class="ibtn createresource" can_deleted="{can_deleted}" href="javascript:;" title="新建分片"><span class="glyphicon glyphicon-indent-left"></span></a>',
	                     		'</td>',
		                     '</tr>'].join('');
        
        var date = $('[name=reservation]').val().split(' 至 ');
        var grid = Grid.init({
	            holder:'trafficList',
	            bodyTemplate:bodyTemplate,
	            dataSource:'/trp/traffic/get_list',
	            pageTemplate:semi.grid.pageTemplate,
	            sendOnPageSize: true
	        });
        
        grid.modifyModel(function(data){
        	/*if(data.bid_type == 'CPM'){
        		data.floor += '<span style="font-size:12px;">元/千次曝光</span>'
        	}*/
    	});
        
        
        //表格数据-流量开关：active 1开   0关 + 是否可删
        grid.onfilled(function(data){
        	grid.data = data;
        	var time = data.time;
        	$('#trafficList').data('time',time);
        	$('#trafficList tbody tr').each(function(){
        		var $tr = $(this), start = $('[start]',$tr).attr('start'), end = $('[end]',$tr).attr('end');
        		if(moment(time).diff(moment(start))<0){//未开始
        			$tr.data('state','0');
        		}else if(moment(end).diff(moment(time))<0){//已结束
        			$tr.data('state','2');
        			$('.editbtn',$tr).addClass('disabled').removeClass('editbtn');
        			$('.delbtn',$tr).addClass('disabled').removeClass('delbtn');
        			$('.createresource',$tr).addClass('disabled').removeClass('createresource');
        		}else{//进行中
        			$tr.data('state','1');
        			$('.delbtn',$tr).addClass('stopbtn').removeClass('delbtn').attr('title','停止').children('span').removeClass('glyphicon-remove').addClass('glyphicon-stop');
        		}
        		if(time==end){//最后一天
        			$('.stopbtn',$tr).addClass('disabled').removeClass('stopbtn');
        		}
        	});
        	
        	$('#trafficList td[active]').each(function(){
        		var $this = $(this), active = $this.attr('active');
        		if(active=='1'){
        			$('.btn:first',$this).removeClass('btn-default').addClass('btn-success');
        			$('.btn:last',$this).removeClass('btn-danger').addClass('btn-default');
        		}else{
        			$('.btn:first',$this).removeClass('btn-success').addClass('btn-default');
        			$('.btn:last',$this).removeClass('btn-default').addClass('btn-danger');
        		}
        	});
        	$('#trafficList .delbtn').each(function(){
        		var $this = $(this), can_deleted = $this.attr('can_deleted');
        		if(can_deleted=='false'){
        			$this.addClass('disabled').removeClass('delbtn');
        			$this.siblings('.editbtn').addClass('disabled').removeClass('editbtn');
        		}
        	});
        	$('.ibtn').tooltip();
        });
        
        /* 数据搜索 */
        var filterData = function(pno){
        	var txt = $('.searchbox-ipt').val(),
            	d = $('[name=reservation]').val().split(' 至 '),
            	size = $('.pageheader [name=measure]').val(),
            	width = '', height = '',
            	pageSize = 20;
        	
        	if(!semi.utils.isEmpty(size)){
	    		size = size.split('x');
	    		width = size[0];
	    		height = size[1];
	    	}
        	if($('select.page-size').size()>0){
        		pageSize = $('select.page-size').val();
        	}
            grid.send({
        		search_text: txt,
        		position_id: position_id,
        		start: d[0],
        		end: d[1],
        		width: width,
	        	height: height,
        		pageSize: pageSize,
        		pageNo: pno || 1
        	});
        };
        filterData();
        
        //按购买周期模糊搜索
        $('input[name=reservation]').daterangepicker({
        	opens: 'left',
            format:'YYYY-MM-DD'
        }, function(start, end, label) {
        	console.log(start.toISOString(), end.toISOString(), label);
        	filterData();
        });
        
        //按名称、属性模糊搜索
        $('.pageheader .searchbox-btn').on('click', function(){
        	filterData();
        });
        $('.pageheader .searchbox-ipt').on('keyup', function(e){
        	if(e.keyCode==semi.keyCode.ENTER){
        		filterData();
        	}
        });
        
        //按尺寸搜索
        $('.pageheader [name=measure]').select2({
        	ajax: {
        		url: '/trp/position/get_position_size/',
        		results: function(data){
        			var resultArr = [{id:'', text:'全部尺寸'}];
        			$.each(data.data, function(i,n){
        				var val = n.width+'x'+n.height;
        				resultArr.push({id:val, text:val});
        			});
        			return {results: resultArr}
        		}
        	}
        }).on('change', function(){
        	filterData();
        });
        
        /* 流量开关 */
        $(document).on('click', '.traffic-open,.traffic-close', function(){
        	var $this = $(this), $tr = $this.parents('tr:first'), traffic_id = $tr.attr('traffic_id'), isloading = $tr.data('loading'), active;
        	if(($this.hasClass('traffic-open') && $this.hasClass('btn-success')) || $this.hasClass('traffic-close') && $this.hasClass('btn-danger') || (!semi.utils.isEmpty(isloading) && isloading))return;
        	$tr.data('loading',true);
        	//active:1为开，0为关
        	if($this.hasClass('traffic-open')){
        		active = 1;
        	}else{
        		active = 0;
        	}
        	$ajax.ajax({
        		url: '/trp/traffic/do_on_off',
        		type: 'post',
        		data: {
        			traffic_id: traffic_id,
        			active: active
        		},
        		success: function(data){
        			if(active==1){
        				$this.addClass('btn-success').siblings('.btn').removeClass('btn-danger');
        			}else{
        				$this.addClass('btn-danger').siblings('.btn').removeClass('btn-success');
        			}
        			$tr.data('loading',false);
        		},
        		error: function(){
        			$dialog.alert('流量开关修改失败，请稍后重试！','warning');
        		}
        	});
        });
        
        /* 修改-dialog */
        require('validate');
        $(document).on('click', '.editbtn', function(){
        	var $this = $(this), $tr = $this.parents('tr:first'), traffic_id = $tr.attr('traffic_id'), state = $tr.data('state');
        	var $dlg = $dialog({
        		title: '广告位流量修改',
        	    width: '700px',
        	    onshow: function() {
        	    	var $d = this, $node = $($d.node);
        	        $ajax.ajax({
                		url: '/trp/traffic/get_one',
                		data: {
                			traffic_id: traffic_id
                		},
                		success: function(data){
                			seajs.log(data)
                			//购买方式CPM:1  CPD:0
                			//平台独占 0是 1否
                			$d.content($('.pop-showtraffic').clone().show()[0]);
                			$('.position_id',$node).html(data.position_id);
                			$('.position_name',$node).html(data.position_name);
                			$('.position_attrs',$node).html(data.position_attrs);
                			$('.mertial_type',$node).html(data.mertial_type);
                			if(/^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(data.size)){
                        		$('.size',$node).html(data.size+'KB');
                        	}else{
                        		data.size = '无限制';
                        		$('.size',$node).html('无限制');
                        	}
                			
                			$('[name=circle]',$node).val(data.start+' 至 '+data.end);
                			
                			$('[name=bid_type]',$node).val(data.bid_type);
                			
                			$('[name=bid_price]',$node).val(data.bid_price);
                			
                			$('[name=pv]',$node).val(data.pv);
                			
                			$('[name=click]',$node).val(data.click);
                			
                			$('[name=shared]',$node).val(data.shared);
                			
                			if(!data.shared){
                				$('.shared_other',$node).hide();
                				$('.shared',$node).addClass('btn-info');
                				$('.noshared',$node).addClass('btn-default');
                				$('[name=floor]',$node).removeClass('required');
                			}else{
                				$('.shared_other',$node).show();
                				$('.shared',$node).addClass('btn-default');
                				$('.noshared',$node).addClass('btn-info');
                				$('[name=floor]',$node).addClass('required');
                			}
                			
                			data.bid_type=='1'?$('.unit',$node).html('元 / 千次曝光'):$('.unit',$node).html('元 / 天');
                			$('[name=floor]',$node).val(data.floor);
                			
	                   	 	$('select[name=bid_type]',$node).on('change', function(){
	                   	 		//购买方式CPM:1  CPD:0
	                   	 		$(this).val()=='1'?$('.unit',$node).html('元 / 千次曝光'):$('.unit',$node).html('元 / 天');
                			});
	                   	 	$('select[name=bid_type]',$node).change();
	                       	$('.shared',$node).on('click', function(){
                				$(this).addClass('btn-info').removeClass('btn-default').siblings('.btn').removeClass('btn-info').addClass('btn-default');
                				$('.shared_other',$node).hide();
                				$('[name=shared]',$node).val(0);
                				$('[name=floor]',$node).removeClass('required');
                			});
        					$('.noshared',$node).on('click', function(){
        						$(this).addClass('btn-info').removeClass('btn-default').siblings('.btn').removeClass('btn-info').addClass('btn-default');
        						$('.shared_other',$node).show();
        						$('[name=shared]',$node).val(1);
        						$('[name=floor]',$node).addClass('required');
                			});
        					if(state=='1'){
        						$('.daterangebox-ipt,select[name=bid_type],[name=bid_price]',$node).attr('disabled','disabled');
        					}else{
        						$('.daterangebox-ipt',$node).daterangepicker({
            			            format:'YYYY-MM-DD',
            			            minDate: $('#trafficList').data('time'),
            			            freezeLeft: (state=='1')
            			        });
        					}
        					
                			$node.initUI();
                		}
                	});
        	    },
        	    okValue: '确定',
        	    ok: function(){
        	 		var $d = this, $node = $($d.node), circle = $('[name=circle]',$node).val().split(' 至 ');
        	 		if(!$('form',$node).valid())return false;
    	 			$ajax.ajax({
                		url: '/trp/traffic/do_update',
                		data: JSON.stringify({
                    		traffic_id: traffic_id,
                    		start: circle[0],
                    		end: circle[1],
                    		bid_type: $('[name=bid_type]',$node).val(),
                    		bid_price: $('[name=bid_price]',$node).val(),
                    		estimated_imp: $('[name=pv]',$node).val(),
                    		estimated_click: $('[name=click]',$node).val(),
                    		shared: $('[name=shared]',$node).val(),
                    		floor: $('[name=floor]',$node).val()
                		}),
                		contentType : "application/json",
                        type : 'POST',
                        dataType : 'json',
                		success: function(data){
                			$d.close().remove();
                			$dialog.alert('修改广告位流量成功！','success');
                			filterData(semi.utils.gridPage(grid));
                		},
                		error: function(){
                			$dialog.alert('修改广告位流量失败，请稍后重试！','warning');
                		}
                	 });
                	 return false;
                },
        	    cancelValue: '取消',
        	    cancel: true
        	}).showModal();
        });
        
        /* 删除/停止-dialog */
        $(document).on('click', '.delbtn,.stopbtn', function(){
        	var $this = $(this), $tr = $this.parents('tr:first'), traffic_id = $tr.attr('traffic_id'), title = ($this.hasClass('delbtn')?'删除':'停止');
        	var $dlg = $dialog.confirm({
        		title: title+'广告位流量',
                content: '您确定要'+title+'该广告位流量吗？',
                ok: function(){
                	var $dlg = this;
                	$ajax.ajax({
                    	url: '/trp/traffic/do_delete/',
                        data: {
                        	traffic_id: $dlg.traffic_id
        				},
                        success: function(){
                        	$dlg.close().remove();
                        	$dialog.alert(title+'广告位流量成功！','success');
                        	filterData(semi.utils.gridPage(grid));
                        },
	                    error: function(){
	                    	$dlg.close().remove();
	                    	$dialog.alert(title+'广告位流量失败，请稍后重试！','warning');
	                    }
                    });
                	return false;
                }
        	});
        	$.extend($dlg,{traffic_id:traffic_id});
        });
        
        /* 查看报表-dialog */
        var $popchart = require('./common/popchart');
        $(document).on('click', '.showchart', function(){
        	var $this = $(this), $tr = $this.parents('tr:first'), traffic_id = $tr.attr('traffic_id');
        	$popchart({
            	title: '广告位流量报表',
            	btn: $this,
            	dataurl: '/trp/traffic/get_report',
            	type: 'traffic',
            	idname: 'traffic_id',
            	idvalue: traffic_id
            });
        });
        
        /* 新建流量分片 */
        $(document).on('click', '.createresource', function(){
        	var $this = $(this), 
        		$tr = $this.parents('tr:first'), 
        		traffic_id = $tr.attr('traffic_id'), 
        		start = $('[start]',$tr).attr('start'),
        		end = $('[end]',$tr).attr('end');
        	
        	if($tr.data('state')==1){
        		start = $('#trafficList').data('time');
        	}
        	require.async('./common/popresource', function($resource){
        		$resource.create({
        			id: traffic_id,
        			start: start,
        			end: end,
        			min: start,
        			max: end
        		});
        	});
        });
    });
});